import { createApp, ComponentPublicInstance, DirectiveBinding } from "vue";
import Loading from "@/components/loading/index.vue";

interface ElType extends HTMLElement {
  instance: ComponentPublicInstance;
}

const vLoading = {
  name: "Loading",
  mounted(el: ElType, binding: DirectiveBinding) {
    // 获取loading提示文案
    const loadingText = el.getAttribute("loading-text") || "";

    const app = createApp(Loading, {
      loadingText: loadingText,
    });
    const instance: ComponentPublicInstance = app.mount(document.createElement("div"));

    instance && (el.instance = instance);
    if (binding.value) append(el);
  },
  updated(el: ElType, binding: DirectiveBinding) {
    if (binding.value !== binding.oldValue) {
      binding.value ? append(el) : remove(el);
    }
  },
};

export function addClass(el: ElType, className: string) {
  // 如果当前元素样式列表中没有className
  if (!el.classList.contains(className)) {
    el.classList.add(className);
  }
}

export function removeClass(el: ElType, className: string) {
  el.classList.remove(className);
}

function append(el: ElType) {
  const style = getComputedStyle(el);
  if (["absolute", "fixed", "relative"].indexOf(style.position) === -1) {
    addClass(el, "position-relative");
  }

  el.appendChild(el.instance.$el);
}

function remove(el: ElType) {
  removeClass(el, "position-relative");
  el.removeChild(el.instance.$el);
}

export default vLoading;
